/*
 * Handle.cpp
 *
 *  Created on: 2014. 6. 25.
 *      Author: jjaehuny
 */

#include "Handle.h"

#include <functional>

#include <boost/asio.hpp>
#include <boost/bind.hpp>

#include <glog/logging.h>

#include "../asio.h"

#include "../Memory/Function_new_Pool.h"
#include "../Memory/Lock_Function_new_Pool.h"

namespace Framework { namespace Timer {

Memory::Function_new_Pool<Handle> s_clsHandlePool_Singlethread;
Memory::Function_new_Pool<Handle> s_clsHandlePool_Multithread;

std::shared_ptr<Handle> create_handle_singlethread()
{
	return s_clsHandlePool_Singlethread.NEW();
}

std::shared_ptr<Handle> create_handle_multithread()
{
	return s_clsHandlePool_Multithread.NEW();
}

} /*Timer*/ } /*Framework*/



namespace Framework { namespace Timer {

struct Handle::Pimple
{
	Pimple() : deadline_timer_(asio::Instance().io_service()) {}
	~Pimple() {}

	void onTime(const boost::system::error_code &ec, void * param);

	boost::asio::deadline_timer deadline_timer_;
	Handle::OBSERVER observer_ = NULL;
	bool _isSetTimer = false;
};

void
Handle::Pimple::onTime(const boost::system::error_code &ec, void * param)
{
	if (!ec)
	{
		LOG(INFO) << __PRETTY_FUNCTION__;
	}
}

Handle::Handle()
: This (new Pimple)
{
	// TODO Auto-generated constructor stub

}

Handle::~Handle() {
	// TODO Auto-generated destructor stub
}

void
Handle::Initialize()
{
	This->observer_ = NULL;
	This->_isSetTimer = false;
}

void
Handle::Finalize()
{
	if (true == This->_isSetTimer)
	{
		this->KillTimer();
	}
}

void
Handle::SetTimer(int milliseconds, int id, OBSERVER observer)
{
	This->observer_ = observer;

	This->deadline_timer_.expires_from_now(boost::posix_time::milliseconds(milliseconds));
	This->deadline_timer_.async_wait(boost::bind(observer, boost::asio::placeholders::error, id));
}

void
Handle::KillTimer()
{
	This->_isSetTimer = false;
	This->deadline_timer_.cancel();
}

} /*Timer*/ } /*Framework*/
